package top.joylee.example.grpc;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.joylee.example.grpc.hello.GreeterGrpc;
import top.joylee.example.grpc.hello.HelloRequest;
import top.joylee.example.grpc.hello.HelloResponse;

import java.util.concurrent.TimeUnit;


/**
 * Hello gRPC 客户端
 */
public class HelloClient {
    private static final Logger log = LoggerFactory.getLogger(HelloClient.class);
    private final GreeterGrpc.GreeterBlockingStub blockingStub;

    public HelloClient(Channel channel) {
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

    public void greet(String name) {
        log.info("*** {} will try to greet ...", name);
        //第一步:设置请求体
        HelloRequest request = HelloRequest
                .newBuilder()
                .setName(name)
                .build();

        //定义response
        HelloResponse response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            log.error("gRPC failed,{}", e.getMessage(), e);
            return;
        }
        log.info("Great:{}", response.getMessage());
    }

    public static void main(String[] args) throws InterruptedException {
        String user = "Joy";
        String target = "localhost:50001";
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
                .usePlaintext()
                .build();
        try {
            for (int i = 1; i <= 5; i++) {
                log.info("...第{}次请求", i);
                HelloClient client = new HelloClient(channel);
                client.greet(user);
                log.info("第{}次请求完成...", i);
                TimeUnit.SECONDS.sleep(2);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
    }
}
